package portal.monitor.controller;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import beans.HttpResultList;
import net.sf.json.JSONObject;
import portal.monitor.dao.MonitorPattern;
import portal.monitor.dao.MonitorSoftware;
import portal.monitor.dao.service.MonitorPatternService;
import portal.monitor.dao.service.MonitorSoftwareService;
import portal.monitor.utils.MonBaseUtils;
import portal.monitor.utils.MonConfig;

@RestController
public class MonitorPatternServlet {
    @Autowired
    MonitorPatternService monitorPatternService;
    @Autowired
    MonitorSoftwareService monitorSoftwareService;
    private HttpResultList result;
    

    @RequestMapping(value = "/MonitorPatternServlet", method = RequestMethod.POST)
    public void PatternService(HttpServletRequest request, HttpServletResponse response) throws IOException {
        result = new HttpResultList();
        String operateType = request.getParameter("operateType");
        try {
            switch (operateType) {
                case "add":
                    addPattern(request);
                    break;
                case "delete":
                    deletePattern(request);
                    break;
                case "alter":
                    alterPattern(request);
                    break;
               case "showPaged":
                    showPaged(request);
                    break;
                case "showDetail":
                    showDetail(request);
                    break;
                case "showAll":
                	showAll(request);
                    break;
            }
        } catch (NullPointerException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST参数错误");
            response.getWriter().print(JSONObject.fromObject(result).toString());
        } catch (NumberFormatException e) {
            e.printStackTrace();
            result.setResult(false);
            result.setMessage("POST数字错误");
        }
        response.getWriter().print(JSONObject.fromObject(result).toString());
    }

    private void addPattern(HttpServletRequest request) throws IOException {
        String patternName = request.getParameter("patternName");
        String patternSoftware = request.getParameter("patternSoftware");
        MonitorPattern monitorPattern = new MonitorPattern(patternName, patternSoftware);
        boolean res = monitorPatternService.insert(monitorPattern) == 1;
        result.setResult(res);

        File startDir = new File(MonConfig.localBase+"start/");
        File killDir = new File(MonConfig.localBase+"kill/");
        if(!startDir.exists()){
        	startDir.mkdirs();
        }   if(!killDir.exists()){
        	killDir.mkdirs();
        }
        
        File startFile = new File(MonConfig.localBase+"start/"+ patternName + ".txt");
        File killFile = new File(MonConfig.localBase+"kill/"+ patternName + ".txt");
        startFile.createNewFile();
        killFile.createNewFile();
        MonBaseUtils.chmod(startFile.getAbsolutePath());
        MonBaseUtils.chmod(killFile.getAbsolutePath());

        String[] temp = patternSoftware.split(",");
        Integer[] softwareIds = new Integer[temp.length];
        for (int i = 0; i < temp.length; i++) {
            softwareIds[i] = Integer.parseInt(temp[i]);
        }
        List<MonitorSoftware> monitorSoftwareList = monitorSoftwareService.selectByPrimaryKeys(softwareIds);
        Writer out1 =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(startFile), "UTF-8"));
        Writer out2 =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(killFile), "UTF-8"));
        StringBuilder startPattern = new StringBuilder();
        StringBuilder killPattern = new StringBuilder();
        for(MonitorSoftware monitorSoftware: monitorSoftwareList){
        	String tmp = monitorSoftware.getSoftwarePath();
        	startPattern.append(tmp).append("\r\n");
        	tmp = tmp.substring(tmp.lastIndexOf("/")+1);
        	killPattern.append(tmp).append("\r\n");
        }
        // 写入数据
        out1.write(String.valueOf(startPattern));
        out1.flush();
        out1.close();
        out2.write(String.valueOf(killPattern));
        out2.flush();
        out2.close();
    }

    private void deletePattern(HttpServletRequest request) {
        Integer patternId = Integer.parseInt(request.getParameter("patternId"));
        String prePatternName = monitorPatternService.selectByPrimaryKey(patternId).getPatternName();
        File oldStartFile = new File(MonConfig.localBase+"start/" + prePatternName + ".txt");
        File oldKillFile = new File(MonConfig.localBase+"kill/" + prePatternName + ".txt");
        if(oldStartFile.exists()){
        	oldStartFile.delete();
        }
        if(oldKillFile.exists()){
        	oldKillFile.delete();
        }
        boolean res = monitorPatternService.deleteByPrimaryKey(patternId) == 1;
        result.setResult(res);
    }

    private void alterPattern(HttpServletRequest request) throws IOException {
        Integer patternId = Integer.parseInt(request.getParameter("patternId"));
        String patternName = request.getParameter("patternName");
        String patternSoftware = request.getParameter("patternSoftware");
        MonitorPattern monitorPattern = new MonitorPattern(patternId, patternName, patternSoftware);
        boolean res = monitorPatternService.updateByPrimaryKey(monitorPattern) == 1;
        result.setResult(res);

        File startDir = new File(MonConfig.localBase+"start/");
        File killDir = new File(MonConfig.localBase+"kill/");
        if(!startDir.exists()){
        	startDir.mkdirs();
        }   if(!killDir.exists()){
        	killDir.mkdirs();
        }
        File startFile = new File(MonConfig.localBase+"start/"+ patternName + ".txt");
        File killFile = new File(MonConfig.localBase+"kill/"+ patternName + ".txt");
        startFile.delete();
        killFile.delete();
        startFile.createNewFile();
        killFile.createNewFile();
        
        String[] temp = patternSoftware.split(",");
        Integer[] softwareIds = new Integer[temp.length];
        for (int i = 0; i < temp.length; i++) {
            softwareIds[i] = Integer.parseInt(temp[i]);
        }
        
        
        List<MonitorSoftware> monitorSoftwareList = monitorSoftwareService.selectByPrimaryKeys(softwareIds);
        Writer out1 =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(startFile), "UTF-8"));
        Writer out2 =new BufferedWriter(new OutputStreamWriter(new FileOutputStream(killFile), "UTF-8"));
        StringBuilder startPattern = new StringBuilder();
        StringBuilder killPattern = new StringBuilder();
        for(MonitorSoftware monitorSoftware: monitorSoftwareList){
        	String tmp = monitorSoftware.getSoftwarePath();
        	startPattern.append(tmp).append("\r\n");
        	tmp = tmp.substring(tmp.lastIndexOf("/")+1);
        	killPattern.append(tmp).append("\r\n");
        }
        // 写入数据
        out1.write(String.valueOf(startPattern));
        out1.flush();
        out1.close();
        out2.write(String.valueOf(killPattern));
        out2.flush();
        out2.close();
    }

    private void showPaged(HttpServletRequest request) {
        Integer currentPage = Integer.parseInt(request.getParameter("currentPage"));
        Integer onePageCount = Integer.parseInt(request.getParameter("onePageCount"));
        List<MonitorPattern> PatternList = monitorPatternService.selectByPage(currentPage, onePageCount);
        List<MonitorPattern> PatternList2 = new ArrayList<MonitorPattern>();
        for(MonitorPattern mp :PatternList){
        	String[] softs = mp.getPatternSoftware().split(",");
        	StringBuilder softStr=new StringBuilder();
        	for(String s:softs){
        		MonitorSoftware ms =monitorSoftwareService.selectByPrimaryKey(Integer.parseInt(s));
        		if(ms!=null){
        			softStr.append(",");
        			softStr.append(ms.getSoftwareName());
        		}
        	}
        	softStr.deleteCharAt(0);
        	mp.setPatternSoftware(softStr.toString());
        	PatternList2.add(mp);
        }
        
        List<Object> objects = new ArrayList<Object>(PatternList2);
        int pageNum = monitorPatternService.pageNum(onePageCount);
        result.setResult(objects.size() > 0);
        result.setMessage(pageNum + "");
        result.setDatas(objects);
    }

    private void showDetail(HttpServletRequest request) {
        Integer patternId = Integer.parseInt(request.getParameter("patternId"));
        MonitorPattern monitorPattern= monitorPatternService.selectByPrimaryKey(patternId);
        List<Object> objects = new ArrayList<>();
        objects.add(monitorPattern);
        result.setResult(monitorPattern != null);
        result.setDatas(objects);
    }
    
    private void showAll(HttpServletRequest request) {
        List<MonitorPattern> PatternList = monitorPatternService.selectAll();
       /* List<MonitorPattern> PatternList2 = new ArrayList<MonitorPattern>();
        for(MonitorPattern mp :PatternList){
        	String[] softs = mp.getPatternSoftware().split(",");
        	StringBuilder softStr=new StringBuilder();
        	for(String s:softs){
        		MonitorSoftware ms =monitorSoftwareService.selectByPrimaryKey(Integer.parseInt(s));
        		if(ms!=null){
        			
        			softStr.append(",");
        			softStr.append(ms.getSoftwareName());
        		}
        	}
        	softStr.deleteCharAt(0);
        	mp.setPatternSoftware(softStr.toString());
        	PatternList2.add(mp);
        }
        */
        List<Object> objects = new ArrayList<Object>(PatternList);
        result.setResult(objects.size() > 0);
        result.setDatas(objects);
    }
}
